package com.bestcem.xm.qdes.handler.impor.type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.qdes.handler.impor.KeyWordHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class KeywordMatrixrowBindHandler implements KeyWordHandler {

    @Override
    public Integer handler(String qType, JSONArray rawItems, JSONObject questionDict) {
        // 矩阵行绑定解析
        //     {id: "10_1",
        //     title: "分组1",
        //     items: [
        //        {gid: 11,
        //        oid: "11",
        //        pGroupId: "10_1"
        //        }]}
        if (rawItems == null || rawItems.isEmpty()) {
            return 0;
        }

        // 选项绑定 标识行没有需要处理的自动
        JSONArray rawMatrixBinds = new JSONArray();
        if (rawItems.size() > 1) {
            for (int i = 1; i < rawItems.size(); i++) {
                rawMatrixBinds.add(rawItems.get(i));
            }
        }

        String rowsRandom = questionDict.getString("options_random"); // 选项顺序: True, "sort", "reverse"
        log.info("Now the optionsRandom = {}", rowsRandom);

        int totalGidCountTmp = 0;
        if ("True".equals(rowsRandom) || "true".equals(rowsRandom)) {
            if (rawMatrixBinds.size() > 0) {
                questionDict.put("rowsBindEffect", true);
            }
            JSONArray retItems = new JSONArray();
            questionDict.put("row_bind_list", retItems);

            for (int i = 0; i < rawMatrixBinds.size(); i++) {
                JSONArray rawMatrixGroup = rawMatrixBinds.getJSONArray(i);
                JSONObject matrixBindDict = new JSONObject();
                Object matrixBindTitle = rawMatrixGroup.get(0);
                List<String> optionCids = (rawMatrixGroup.size() > 1 && StringUtils.isNotEmpty(rawMatrixGroup.getString(1).trim()))
                    ? Arrays.stream(rawMatrixGroup.getString(1).trim().split(",")).collect(Collectors.toList())
                    : new ArrayList<>();

                JSONArray itemsJs = new JSONArray();
                for (String cid : optionCids) {
                    if (StringUtils.isNotEmpty(cid)) {
                        JSONObject cidJs = new JSONObject();
                        cidJs.put("oid", cid);
                        itemsJs.add(cidJs);
                    }
                }
                matrixBindDict.put("items", itemsJs);
                matrixBindDict.put("title", matrixBindTitle);
                retItems.add(matrixBindDict);
            }
        }
        return totalGidCountTmp;
    }

    @Override
    public String getType() {
        return "矩阵行绑定";
    }
}
